/*
 * Created on 2009-9-14
 * Copyright 2009 by www.xfok.net. All Rights Reserved
 *
 */

package com.swcw.platform.constants;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.swcw.platform.external.constants.SysPropertiesUtil;
import com.jcraft.jsch.ChannelSftp.LsEntry;

/**
 * @author YangHua 转载请注明出处：http://www.xfok.net/2009/10/124485.html
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class MySFTP {

	/**
	 * 连接sftp服务器
	 * 
	 * @param host
	 *            主机
	 * @param port
	 *            端口
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return
	 */
	public static ChannelSftp connect() {
		
		ChannelSftp sftp = null;
		String host = SysPropertiesUtil.getProperty("host");
		String username = SysPropertiesUtil.getProperty("userName");
		String password = SysPropertiesUtil.getProperty("pwd");
		String po = SysPropertiesUtil.getProperty("port");
		int port = Integer.parseInt(po);
		try {
			JSch jsch = new JSch();
			jsch.getSession(username, host, port);
			Session sshSession = jsch.getSession(username, host, port);
			//System.out.println("开始连接服务器");
			sshSession.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(sshConfig);
			sshSession.connect();
			//System.out.println("密码正确");
			//System.out.println("开始链接ftp");
			Channel channel = sshSession.openChannel("sftp");
			channel.connect();
			sftp = (ChannelSftp) channel;
			//System.out.println("连接成功" + host + ".");
		} catch (Exception e) {
			System.out.println("连接资源服务器失败，数据没有备份！1");
		}
		return sftp;
	}

	/**
	 * 上传文件
	 * 
	 * @param directory
	 *            上传的目录
	 * @param uploadFile
	 *            要上传的文件
	 * @param sftp
	 */
	public static void upload(String directory,String newFileName, InputStream localFilePath, ChannelSftp sftp) {
		System.out.println(directory);
		try{
			sftp.ls(directory); //首先查看下目录，如果不存在，系统会被错，捕获这个错，生成新的目录。
		}catch(Exception e1){
			try {
				sftp.mkdir(directory);
			} catch (SftpException e) {
				System.out.println("连接资源服务器失败，数据没有备份！2");
			}
		}
		try {
			sftp.cd(directory);
			sftp.put(localFilePath, newFileName);
		} catch (Exception e) {
			System.out.println("连接资源服务器失败，数据没有备份！3");
		}finally {
			if(localFilePath != null){
				try {
					localFilePath.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(sftp!=null){
				System.out.println("关闭连接2");
				try {
					sftp.getSession().disconnect();
				} catch (JSchException e) {
				}
				sftp.quit();
				sftp.disconnect();
			}
		}
	}

	/**
	 * 下载文件
	 * 
	 * @param directory
	 *            下载目录
	 * @param downloadFile
	 *            下载的文件
	 * @param saveFile
	 *            存在本地的路径
	 * @param sftp
	 */
	public static void download(String directory, String downloadFile,
			String saveFile, ChannelSftp sftp) {
		try {
			sftp.cd(directory);
			File file = new File(saveFile);
			sftp.get(downloadFile, new FileOutputStream(file));
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(sftp!=null){
				System.out.println("关闭连接2");
				try {
					sftp.getSession().disconnect();
				} catch (JSchException e) {
				}
				sftp.quit();
				sftp.disconnect();
			}
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param deleteFile
	 *            要删除的文件
	 * @param sftp
	 */
	public static void delete(String deleteFile, ChannelSftp sftp) {
		try {
			sftp.rm(deleteFile);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(sftp!=null){
				System.out.println("关闭连接2");
				try {
					sftp.getSession().disconnect();
				} catch (JSchException e) {
				}
				sftp.quit();
				sftp.disconnect();
			}
		}
	}

	/**
	 * 列出目录下的文件
	 * 
	 * @param directory
	 *            要列出的目录
	 * @param sftp
	 * @return
	 * @throws SftpException
	 */
	public Vector listFiles(String directory, ChannelSftp sftp)
			throws SftpException {
		return sftp.ls(directory);
	}

	public static void main(String[] args) {
		// String directory = "/home/httpd/test/";
		// String uploadFile = "D:\\tmp\\upload.txt";
		// String downloadFile = "upload.txt";
		// String saveFile = "D:\\tmp\\download.txt";
		// String deleteFile = "delete.txt";
		ChannelSftp sftp = MySFTP.connect();
		try {
			Vector<LsEntry> lss = sftp.ls("/home/jshx/apache-tomcat-8.0.24_2/webapps/upload");
			for (LsEntry str : lss) {
				System.out.println(str.getFilename());
			}

		} catch (SftpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		sftp.disconnect();
		// sf.upload(directory, uploadFile, sftp);
		// sf.download(directory, downloadFile, saveFile, sftp);
		// sf.delete(directory, deleteFile, sftp);
		/*
		 * try{ sftp.cd(directory); sftp.mkdir("ss");
		 * System.out.println("finished"); }catch(Exception e){
		 * e.printStackTrace(); }
		 */
	}
	
}